/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.chromium.latency.walt;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import androidx.fragment.app.Fragment;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;

import java.io.IOException;
import java.util.Locale;


/**
 * This screen allows to perform different tasks useful for diagnostics.
 */
public class DiagnosticsFragment extends Fragment implements View.OnClickListener {

    private SimpleLogger logger;
    private TextView logTextView;
    private Spinner debugSpinner;
    private WaltDevice waltDevice;
    private Handler handler = new Handler();
    private ImageButton debugButton;
    private AudioTest audioTest;

    private BroadcastReceiver logReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String msg = intent.getStringExtra("message");
            DiagnosticsFragment.this.appendLogText(msg);
        }
    };

    public DiagnosticsFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        logger = SimpleLogger.getInstance(getContext());
        // Inflate the layout for this fragment
        final View view = inflater.inflate(R.layout.fragment_diagnostics, container, false);
        logTextView = (TextView) view.findViewById(R.id.txt_log_diag);

        ArrayAdapter<CharSequence> debugAdapter = ArrayAdapter.createFromResource(getContext(),
                R.array.debug_item_name, android.R.layout.simple_spinner_item);
        debugAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);

        debugSpinner = (Spinner) view.findViewById(R.id.spinner_debug_mode);
        debugSpinner.setAdapter(debugAdapter);

        waltDevice = WaltDevice.getInstance(getContext());
        debugButton = (ImageButton) view.findViewById(R.id.button_start_debug);
        debugButton.setOnClickListener(this);

        audioTest = new AudioTest(getActivity());

        return view;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() != R.id.button_start_debug) {
            return;
        }
        final int spinnerPosition = debugSpinner.getSelectedItemPosition();
//        logger.log("start debug item : " + spinnerPosition);

        if (spinnerPosition == 0) {
            sendWaltCMD(WaltDevice.CMD_SAMPLE_ALL);
        } else if (spinnerPosition == 1) {
            sendWaltCMD(WaltDevice.CMD_BEEP);
            handler.postDelayed(stopBeep, 1000);
        } else if (spinnerPosition == 2) {
            sendWaltCMD(WaltDevice.CMD_BEEP);
        } else if (spinnerPosition == 3) {
            sendWaltCMD(WaltDevice.CMD_BEEP_STOP);
        } else if (spinnerPosition == 4) {
            handler.postDelayed(startPlayTone, 100);
        } else if (spinnerPosition == 5) {
            audioTest.stopTests();
            handler.removeCallbacks(startPlayTone);
        } else {
            logger.log("ERROR: Spinner position is out of range");
        }
    }

    public void sendWaltCMD(char cmd) {
        long t1 = waltDevice.clock.micros();
        logger.log(String.format(Locale.US,"----> CMD [%c]", cmd));
        try {
            String res = waltDevice.command(cmd);
            long dt = waltDevice.clock.micros() - t1;
            logger.log(String.format(Locale.US,"<---- reply in %.1fms：\t %s",dt / 1000., res));
        } catch (IOException e) {
            logger.log(String.format(Locale.US,"Error sending CMD [%c]: %s",cmd, e.getMessage()));
        }
    }

    Runnable stopBeep = () -> sendWaltCMD(WaltDevice.CMD_BEEP_STOP);
    Runnable startPlayTone = new Runnable() {
        @Override
        public void run() {
            audioTest.playTone();
            handler.postDelayed(startPlayTone, 100);
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        logTextView.setMovementMethod(new ScrollingMovementMethod());
        logTextView.setText(logger.getLogText());
        logger.registerReceiver(logReceiver);
        debugButton.setOnClickListener(this);
    }

    @Override
    public void onPause() {
        logger.unregisterReceiver(logReceiver);
        super.onPause();
    }


    public void appendLogText(String msg) {
        logTextView.append(msg + "\n");
    }
}
